package gao.xiaolei.controller;

import gao.xiaolei.quertz.PrintWordJob;
import gao.xiaolei.quertz.QuartzJobService;
import gao.xiaolei.quertz.TaskDefine;
import gao.xiaolei.util.CronUtil;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/quartz")
public class QuartzController{

    @Resource(name = "QuartzJobService")
    QuartzJobService quartzJobService;

//    @Autowired
//    private StreamClient streamClient;


    @GetMapping("/list/{projectId}")
    public List<String> getExitsJob(@PathVariable("projectId") String projectId) throws SchedulerException {
        Set<JobKey> keySet = quartzJobService.getKeyByGroup(projectId);
        List<String> detail = new ArrayList<>(keySet.size());
        for (JobKey k : keySet) {
            JobDetail jobDetail = quartzJobService.getJobDetail(k);
            detail.add(jobDetail.getDescription());
        }
        return detail;
    }

    @GetMapping("createJob/{groupId}/{key}/{text}")
    public void createJob(@PathVariable("groupId") String groupId,
                          @PathVariable("key") String key,
                          @PathVariable("text") String text) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(key, groupId);
        TaskDefine taskDefine = TaskDefine.builder()
                .jobKey(jobKey)
                .cronExpression(CronUtil.getCron(LocalDateTime.now().plusMinutes(1)))   //定时任务 的cron表达式00 37 23 18 2 ? 2020
                .jobClass(PrintWordJob.class)   //定时任务 的具体执行逻辑
                .description(text)    //定时任务 的描述
                .build();
        quartzJobService.scheduleJob(taskDefine);
    }


//    @PostMapping("/sendMessage")
//    public void testSend(@RequestBody JobkeyDto jobkeyDto){
//        streamClient.output().send(MessageBuilder.withPayload(jobkeyDto).build());
//    }

}
